/*
 * Copyright 2010 Kevin L'Huillier <klhuillier@gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.lhuillier.pwsafe.model;


import java.util.Arrays;


/**
 * Holds raw <code>byte[]</code> data.
 * <p>
 * This is used primarily to hold data of unknown types.
 * <p>
 * This is an immutable value object.
 */
public class RawField {
    private static final long serialVersionUID = -4536918266510474020L;
    private final byte typeId;
    private final byte[] data;

    /**
     * @throws NullPointerException if data is null
     */
    public RawField(byte typeId, byte[] data) {
        this.typeId = typeId;
        this.data = data.clone();
    }

    public byte getTypeId() {
        return typeId;
    }

    public byte[] getValue() {
        return data.clone();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        } else if (obj == null || !getClass().equals(obj.getClass())) {
            return false;
        }
        RawField other = (RawField) obj;
        if (typeId != other.typeId) {
            return false;
        }
        return Arrays.equals(data, other.data);
    }

    @Override
    public int hashCode() {
        int result = typeId;
        for (byte b : data) {
            result *= 31;
            result += b;
        }
        return result;
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder(getClass().getName()).
                append("[typeId=").append(typeId).append(";data=");
        if (data.length > 0) {
            result.append(String.format("%02x", data[0]));
        }
        for (int i = 1; i < data.length; i++) {
            result.append(String.format(" %02x", data[i]));
        }
        return result.toString();
    }
}
